<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use Request;
use Input;
use DB;
use Session;
use Redirect;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    // public function __construct()
    // {
    //     $this->middleware('auth');
    // }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //throw new \Exception('lsdlfsfa',1);
        return view('home')->withArticles(\App\Articles::all());
    }

    public function hello(){
        return view('admin.hello');
    }

    public function login(){
        if($this->checklogin()){
            return Redirect('/hello');
        }else{
            return view('admin.login');
        }
        
    }

    public function logindeal(){
        $username=trim(Request::input('name'));
        $password=md5(trim(Request::input('password')));
        $ref_url=Request::url();
            $remember=Request::input('remember');//是否自动登录标示
            $err_msg='';
        if($username==''||$password==''){
             $err_msg="用户名和密码都不能为空";
         }else{
             //$row=DB::table('users')->where('name','=',$username)->get();
          $row = DB::select('select * from users where name = ?', [$username]);
              //dd($row);die;
          if(empty($row)){
            $err_msg="用户名不正确";
        }else{

          $pwd = md5($row[0]->password);
          if($password!=$pwd){
            $err_msg="密码不正确";
        }else{
            Session('name',$username);
                       if(!empty($remember)){//如果用户选择了，记录登录状态就把用户名和加了密的密码放到cookie里面
                           setcookie("username",$username,time()+3600*24*365);
                           setcookie("password",$password,time()+3600*24*365);
                           return Redirect('/hello');
                       }
                       return Redirect('/hello');
                   }

               }
           }

       }

        //检查用户是否登录
       public function checklogin(){
           if(empty(Session('name'))){
            //检查一下session是不是为空
           //dd('1111');
          if(empty($_COOKIE['username'])||empty($_COOKIE['password'])){//如果session为空，并且用户没有选择记录登录状        
            return false;//转到登录页面，记录请求的url，登录后跳转过去，用户体验好。
          }else{//用户选择了记住登录状态
               $name = $_COOKIE['username'];
               $password = $_COOKIE['password'];//去取用户的个人资料
               $row = DB::select(' select * from users where name = ?',[$name]);
               $pwd = md5($row[0]->password);
              if($password == $pwd){//用户名密码不对没到取到信息，转到登录页面
                Session('name',$name);
                return true;
            }else{
                return false;
            }
        }
   }else{
           Session('name',$name);//用户名和密码对了，把用户的个人资料放到session里面
           return true;
       }
}

}
